package net.butfly.bus.filter;

import net.butfly.bus.Error;
import net.butfly.bus.Request;
import net.butfly.bus.Response;
import net.butfly.bus.context.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggerFilter extends FilterBase implements Filter {
	private final Logger logger = LoggerFactory.getLogger("EBOX");

	@Override
	public void execute(Request request, Response response) throws Exception {
		String marker = "Bus{" + side.name() + ":" + Context.getFlowNo() + "}";
		long now = System.currentTimeMillis();
		logger.debug(marker + "Bus invoking begin...");
		logger.debug(marker + getDebugDetail(request));
		try {
			super.execute(request, response);
		} finally {
			long spent = System.currentTimeMillis() - now;
			Error err = response.getError();
			if (err != null)
				logger.error("Bus error: \n" + err.toString());
			logger.debug(marker + "调用结束，耗时 " + spent + "毫秒.");
		}
	}

	private String getDebugDetail(Request request) {
		StringBuilder sb = new StringBuilder();
		sb.append("\n\tBus request detail: ").append("\n\t\tcontext: ").append(Context.CURRENT.toString())
				.append("\n\t\ttx code: ").append(request.code()).append("\n\t\ttx version").append(request.version())
				.append("\n\t\trequest arguments: ");
		if (request.arguments() != null)
			for (Object to : request.arguments())
				if (null != to)
					sb.append("\n\t\t\t").append(to);
				else
					sb.append("\n\t\t\t").append("[NULL]");
		else
			sb.append("[NULL]");
		return sb.toString();
	}
}
